package com.rc.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Random;
import java.util.regex.Pattern;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.rc.activity.Login;
import com.rc.activity.R;
import com.rc.activity.ReceiptBox;
import com.rc.activity.dao.DaoMaster;
import com.rc.activity.dao.tbl_User;
import com.rc.activity.dao.DaoMaster.DevOpenHelper;
import com.rc.db.DatabaseSupport;
import com.telpoo.frame.ui.BaseFragment;

@SuppressLint("SimpleDateFormat")
public class Util {

	@SuppressLint("ResourceAsColor")
	public static void setError(EditText myedittext, String text) {
		int ecolor = Color.RED; // whatever color you want
		ForegroundColorSpan fgcspan = new ForegroundColorSpan(ecolor);
		SpannableStringBuilder ssbuilder = new SpannableStringBuilder(text);
		ssbuilder.setSpan(fgcspan, 0, text.length(), 0);
		myedittext.requestFocus();
		myedittext.setError(ssbuilder);
	}

	public static void setVisiable(EditText myedittext) {
		myedittext.setError(null);
	}

	public static String decodeURL(String url) {
		url = url.replace(" ", "+");
		url = url.replace("\"", "%22");
		return url;
	}

	public static boolean validateText(TextView txtText) {
		if (txtText != null) {
			if (!"".equals(txtText.getText().toString())) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}

	public static boolean validateEmail(TextView txtText) {
		Pattern pattern = Patterns.EMAIL_ADDRESS;
		return pattern.matcher(txtText.getText().toString()).matches();
	}

	public static boolean validateLeng(TextView txtText) {
		if (txtText.getText().toString().length() >= 6) {
			return true;
		} else {
			return false;
		}
	}

	public static String saveImageToExternalStorage(Bitmap image, String mfile,
			Context context) {
		String fullPath = Const.FILE_KEY;
		try {
			File dir = new File(fullPath);
			if (!dir.exists()) {
				dir.mkdirs();
			}

			OutputStream fOut = null;
			File file = new File(fullPath, mfile);
			file.createNewFile();
			fOut = new FileOutputStream(file);

			try {
				image.compress(Bitmap.CompressFormat.JPEG, 90, fOut);
				fOut.flush();
				fOut.close();

				MediaStore.Images.Media.insertImage(
						context.getContentResolver(), file.getAbsolutePath(),
						file.getName(), file.getName());
			} catch (OutOfMemoryError e) {
				// TODO: handle exception
				e.printStackTrace();
			}

			return mfile;

		} catch (Exception e) {
			return "";
		}
	}

	public static String getTodaysDate() {

		final Calendar c = Calendar.getInstance();
		int todaysDate = (c.get(Calendar.YEAR) * 10000)
				+ ((c.get(Calendar.MONTH) + 1) * 100)
				+ (c.get(Calendar.DAY_OF_MONTH));
		Log.w("DATE:", String.valueOf(todaysDate));
		return (String.valueOf(todaysDate));

	}

	public static String getCurrentTime() {

		final Calendar c = Calendar.getInstance();
		int currentTime = (c.get(Calendar.HOUR_OF_DAY) * 10000)
				+ (c.get(Calendar.MINUTE) * 100) + (c.get(Calendar.SECOND));
		Log.w("TIME:", String.valueOf(currentTime));
		return (String.valueOf(currentTime));

	}

	// Push fragment
	public static void pushFragmentReceiptBox(Fragment fragment,
			FragmentActivity at, String isChild) {
		FragmentTransaction transaction = at.getSupportFragmentManager()
				.beginTransaction();
		if (isChild.equals("2")) {
			transaction.setCustomAnimations(R.anim.right_left,
					R.anim.exit_right_left, R.anim.pop_enter_left_right,
					R.anim.pop_exit_left_right);
		} else if (isChild.equals("3")) {
			transaction.setCustomAnimations(R.anim.left_right,
					R.anim.exit_left_right, R.anim.pop_enter_right_left,
					R.anim.pop_exit_right_left);
		}
		transaction.replace(R.id.content_frame, fragment).commit();
		try {
			((ReceiptBox) at).showingFragment = (BaseFragment) fragment;
		} catch (ClassCastException e) {
			// TODO: handle exception
			e.printStackTrace();
		}

	}

	public static String getDefaultInfor() {
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat dft = null;
		dft = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault());
		String strDate = dft.format(cal.getTime());
		return strDate;
	}

	public static void HidenKeyBoard(Activity at) {
		InputMethodManager inputManager = (InputMethodManager) at
				.getSystemService(Context.INPUT_METHOD_SERVICE);

		// check if no view has focus:
		View v = at.getCurrentFocus();
		if (v == null)
			return;

		inputManager.hideSoftInputFromWindow(v.getWindowToken(),
				InputMethodManager.HIDE_NOT_ALWAYS);
	}

	public static void setListViewHeightBasedOnChildren(ListView listView) {
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null)
			return;

		int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(),
				MeasureSpec.UNSPECIFIED);
		int totalHeight = 0;
		View view = null;
		for (int i = 0; i < listAdapter.getCount(); i++) {
			view = listAdapter.getView(i, view, listView);
			if (i == 0)
				view.setLayoutParams(new ViewGroup.LayoutParams(desiredWidth,
						LayoutParams.WRAP_CONTENT));

			view.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
			totalHeight += view.getMeasuredHeight();
		}
		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight
				+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		listView.setLayoutParams(params);
		listView.requestLayout();
	}

	public static BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
		@SuppressWarnings("deprecation")
		public void onReceive(Context context, Intent intent) {

			NetworkInfo currentNetworkInfo = (NetworkInfo) intent
					.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
			NetworkInfo otherNetworkInfo = (NetworkInfo) intent
					.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);

			if (currentNetworkInfo.isConnected()) {
				Toast.makeText(context, context.getString(R.string.connected),
						1).show();
			} else {
				Toast.makeText(context,
						context.getString(R.string.no_connection), 1).show();
			}
		}

	};

	public static boolean isNetworkActivated(Context context) {
		try {
			if (context == null) {
				return false;
			}
			ConnectivityManager connectivityManager = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = connectivityManager
					.getActiveNetworkInfo();
			return networkInfo != null && networkInfo.isConnected();
		} catch (RuntimeException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return false;

	}

	public static String getDateByDateTimePicker(DatePicker dPicker) {
		String date = String.valueOf(dPicker.getDayOfMonth());
		if (date.length() < 2) {
			date = "0" + date;
		}
		String month = String.valueOf(dPicker.getMonth() + 1);
		if (month.length() < 2) {
			month = "0" + month;
		}
		String date_choose = date + "/" + month + "/" + dPicker.getYear();
		return date_choose;
	}

	/**
	 * Save image
	 */
	public static String SaveImage(Bitmap finalBitmap, String fileName) {

		File myDir = new File(Const.FILE_KEY);
		myDir.mkdirs();
		Random generator = new Random();
		int n = 10000;
		n = generator.nextInt(n);
		File file = new File(myDir, fileName);
		if (file.exists())
			file.delete();
		try {
			FileOutputStream out = new FileOutputStream(file);
			finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
			out.flush();
			out.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
		return Const.FILE_KEY + fileName;

	}

	public static String addDate(String datenow, int number) {

		SimpleDateFormat curFormater = new SimpleDateFormat("dd-MM-yyyy");
		Date dateObj;
		try {
			dateObj = curFormater.parse(datenow);
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(dateObj);
			calendar.add(Calendar.DATE, number);
			SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy");
			String output = sdf1.format(calendar.getTime());
			return output;
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "";
		}

	}

	public static Bitmap DisplayImageSDCard(String mFile, Context ct) {
		Bitmap myBitmap = BitmapFactory.decodeFile(mFile);

		return myBitmap;
	}

	public static String addDateTime(int number) {
		Calendar c = Calendar.getInstance();
		c.add(Calendar.DATE, number);
		SimpleDateFormat sdf1 = new SimpleDateFormat("MM-dd-yyyy");
		String output = sdf1.format(c.getTime());
		return output;
	}

	public static String removeDateTime(int number, String format) {
		Calendar c = Calendar.getInstance();
		number = 0 - number;
		c.add(Calendar.DATE, number);
		SimpleDateFormat sdf1 = new SimpleDateFormat(format);
		String output = sdf1.format(c.getTime());
		return output;
	}

	public static long removeDateTime(int number) {
		Calendar c = Calendar.getInstance();
		number = 0 - number;
		c.add(Calendar.DATE, number);
		Timestamp timestamp = new Timestamp(c.getTime().getTime());
		return timestamp.getTime();
	}

	public static boolean createDirIfNotExists() {
		File folder = new File(Environment.getExternalStorageDirectory()
				+ "/rci");
		boolean success = true;
		if (!folder.exists()) {
			success = folder.mkdir();
		}
		return success;
	}

	public static String formateDateFromstring(String inputFormat,
			String outputFormat, String inputDate) {

		Date parsed = null;
		String outputDate = "";

		SimpleDateFormat df_input = new SimpleDateFormat(inputFormat,
				java.util.Locale.getDefault());
		SimpleDateFormat df_output = new SimpleDateFormat(outputFormat,
				java.util.Locale.getDefault());

		try {
			parsed = df_input.parse(inputDate);
			outputDate = df_output.format(parsed);

		} catch (ParseException e) {
			e.printStackTrace();
			return "";
		} catch (NullPointerException e) {
			// TODO: handle exception
		}
		return outputDate;
	}

	public static int parseDateForInt(String dateTime) {
		dateTime = dateTime.replace("/", "-");
		dateTime = formateDateFromstring("dd-MM-yyyy", "yyyy-MM-dd", dateTime);
		dateTime = dateTime.replace("-", "");
		dateTime = dateTime.replace("/", "");
		if (dateTime != null && !"".equals(dateTime)) {
			return Integer.valueOf(dateTime);
		}
		return 0;
	}

	public static long parseDateForReceipt(String dateTime) {
		dateTime = dateTime.replace("-", "");
		if (dateTime != null && !"".equals(dateTime)) {
			return Long.valueOf(dateTime);
		}
		return 0;
	}

	/**
	 * get ReceiptType by Text
	 * 
	 */

	public static int getReceiptTypeByText(Context ct, String mText) {
		int mReceiptType = 0;
		if (mText.equals(ct.getString(R.string.all_receipts))) {
			mReceiptType = 0;
		} else if (mText.equals(ct.getString(R.string.paper_receipts))) {
			mReceiptType = 3;
		} else if (mText.equals(ct.getString(R.string.manual_receipts))) {
			mReceiptType = 4;
		} else if (mText.equals(ct.getString(R.string.email_receipts))) {
			mReceiptType = 2;
		} else if (mText.equals(ct.getString(R.string.paper_invoice))) {
			mReceiptType = 6;
		}
		return mReceiptType;
	}

	/**
	 * get Text by ReceiptType
	 * 
	 */

	public static String getReceiptTypeByInt(Context ct, int mReceiptType) {
		String mText = "";
		if (mReceiptType == 0) {
			mText = (ct.getString(R.string.all_receipts));
		} else if (mReceiptType == 3) {
			mText = (ct.getString(R.string.paper_receipts));
		} else if (mReceiptType == 4) {
			mText = (ct.getString(R.string.manual_receipts));
		} else if (mReceiptType == 2) {
			mText = (ct.getString(R.string.email_receipts));
		} else if (mReceiptType == 6) {
			mText = ct.getString(R.string.paper_invoice);
		}
		return mText;
	}

	/**
	 * convert bitmap to byte[]
	 */
	@SuppressLint("NewApi")
	public static byte[] convertBitMapToByte(Bitmap bitmap) {
		// Create the buffer with the correct size
		int iBytes = bitmap.getWidth() * bitmap.getHeight() * 4;
		ByteBuffer buffer = ByteBuffer.allocate(iBytes);

		// Log.e("DBG", buffer.remaining()+""); -- Returns a correct number
		// based on dimensions
		// Copy to buffer and then into byte array
		bitmap.copyPixelsToBuffer(buffer);
		// Log.e("DBG", buffer.remaining()+""); -- Returns 0
		return buffer.array();
	}

	/**
	 * check date time if date and month < 10 + "0"
	 */
	public static String validateDateMonth(int datemonth) {
		if (String.valueOf(datemonth).length() < 2) {
			return "0" + String.valueOf(datemonth);
		}
		return datemonth + "";
	}

	public static ArrayList<String> readFromfile(Context context,
			String fileName) {
		StringBuilder returnString = new StringBuilder();
		InputStream fIn = null;
		ArrayList<String> arrString = new ArrayList<String>();
		InputStreamReader isr = null;
		BufferedReader input = null;
		try {
			fIn = context.getResources().getAssets()
					.open(fileName, Context.MODE_WORLD_READABLE);
			isr = new InputStreamReader(fIn);
			input = new BufferedReader(isr);
			String line = "";
			while ((line = input.readLine()) != null) {
				arrString.add(line.trim());
			}
		} catch (Exception e) {
			e.getMessage();
		} finally {
			try {
				if (isr != null)
					isr.close();
				if (fIn != null)
					fIn.close();
				if (input != null)
					input.close();
			} catch (Exception e2) {
				e2.getMessage();
			}
		}
		return arrString;
	}

	public static void logOut(Activity ct) {
		File file = new File(Const.FILE_KEY);
		deleteDirectory(file);
		SQLiteDatabase db;
		DevOpenHelper helper = new DaoMaster.DevOpenHelper(ct,
				Const.DATABASE_NAME, null);
		db = helper.getWritableDatabase();
		DaoMaster.dropAllTables(db, false);
		DaoMaster.createAllTables(db, false);
		Login.callIntent(ct);
	}

	public static String formatStringFloat(float number) {
		String text = String.format("%.2f", number);
		text = text.replace(",", ".");
		return text;
	}

	public static float convertFloat(String number) {
		if (number == null || "".equals(number) || number.equals("null")) {
			return 0;
		} else {
			return Float.valueOf(number);
		}
	}

	public static boolean deleteDirectory(File path) {

		if (path.exists()) {
			File[] files = path.listFiles();
			if (files == null) {
				return true;
			}
			for (int i = 0; i < files.length; i++) {
				if (files[i].isDirectory()) {
					deleteDirectory(files[i]);
				} else {
					files[i].delete();
				}
			}
		}
		return (path.delete());
	}

	public static String formatString(String text) {
		if ("null".equals(text)) {
			return "";
		}
		return text;
	}

	public static boolean validateFloat2Decimal(String text) {
		if (text.indexOf(".") >= 0) {
			String[] lText = text.split("\\.");
			if (lText.length == 2) {
				text = lText[1];
				if (text.length() > 2) {
					return false;
				}
			}

		}

		return true;
	}

	public static String validateNameImage(Context ct) {
		tbl_User objUser = new tbl_User();
		objUser = DatabaseSupport.getTbl_User(ct);
		String nameImage = objUser.getUserID() + "_r_"
				+ Calendar.getInstance().getTime().getTime() + ".jpg";
		return nameImage;
	}
}
